<script setup lang="ts">
import { h, reactive, ref, watch } from 'vue';
import type { DataTableColumns } from 'naive-ui';
import { NTag, NButton } from 'naive-ui';
import { fetchApiCallLogs } from '@/service/api';
import { useBoolean } from '@sa/hooks';

defineOptions({
  name: 'ApiLogsDrawer'
});

interface Props {
  apiId: number | null;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', { required: true });

const { bool: loading, setTrue: startLoading, setFalse: endLoading } = useBoolean();

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
});

const tableData = ref<any[]>([]);
const total = ref(0);

const columns: DataTableColumns<any> = [
  { key: 'id', title: 'ID', width: 80, align: 'center' },
  { key: 'caller', title: '调用方', width: 120, ellipsis: { tooltip: true } },
  { key: 'callerIp', title: '调用IP', width: 140, ellipsis: { tooltip: true } },
  {
    key: 'statusCode',
    title: '状态码',
    width: 100,
    align: 'center',
    render: row => {
      const type = row.statusCode === 200 ? 'success' : 'error';
      return h(NTag, { type }, () => row.statusCode);
    }
  },
  {
    key: 'responseTime',
    title: '响应时间',
    width: 120,
    align: 'center',
    render: row => `${row.responseTime}ms`
  },
  { key: 'callTime', title: '调用时间', width: 180, ellipsis: { tooltip: true } },
  {
    key: 'actions',
    title: '操作',
    width: 100,
    align: 'center',
    fixed: 'right',
    render: row => {
      return h(NButton, { 
        size: "small", 
        onClick: () => handleViewDetail(row) 
      }, () => '详情');
    }
  }
];

const detailModalVisible = ref(false);
const detailData = ref<any>(null);

watch(visible, () => {
  if (visible.value && props.apiId) {
    getTableData();
  }
});

async function getTableData() {
  if (!props.apiId) return;

  startLoading();
  try {
    const { data } = await fetchApiCallLogs(props.apiId, queryParams);
    if (data) {
      tableData.value = data.rows || [];
      total.value = data.total || 0;
    }
  } finally {
    endLoading();
  }
}

function handleViewDetail(row: any) {
  detailData.value = row;
  detailModalVisible.value = true;
}

function handlePageChange(page: number) {
  queryParams.pageNum = page;
  getTableData();
}

function handlePageSizeChange(pageSize: number) {
  queryParams.pageSize = pageSize;
  queryParams.pageNum = 1;
  getTableData();
}

function handleClose() {
  visible.value = false;
}
</script>

<template>
  <NDrawer v-model:show="visible" title="API调用日志" :width="1000">
    <NDrawerContent closable>
      <div class="h-full flex-col">
        <NDataTable
          :columns="columns"
          :data="tableData"
          :loading="loading"
          :scroll-x="900"
          :flex-height="true"
          class="sm:h-0 sm:flex-1-hidden"
        />

        <NPagination
          v-model:page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :item-count="total"
          :page-sizes="[10, 20, 30, 50]"
          show-size-picker
          class="mt-10px"
          @update:page="handlePageChange"
          @update:page-size="handlePageSizeChange"
        />
      </div>

      <template #footer>
        <NSpace justify="end">
          <NButton @click="handleClose">关闭</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>

  <!-- 详情弹窗 -->
  <NModal v-model:show="detailModalVisible" preset="card" title="调用详情" style="width: 800px">
    <div v-if="detailData" class="flex-col gap-16px">
      <NDescriptions :column="2" bordered>
        <NDescriptionsItem label="调用方">{{ detailData.caller }}</NDescriptionsItem>
        <NDescriptionsItem label="调用IP">{{ detailData.callerIp }}</NDescriptionsItem>
        <NDescriptionsItem label="状态码">
          <NTag :type="detailData.statusCode === 200 ? 'success' : 'error'">
            {{ detailData.statusCode }}
          </NTag>
        </NDescriptionsItem>
        <NDescriptionsItem label="响应时间">{{ detailData.responseTime }}ms</NDescriptionsItem>
        <NDescriptionsItem label="调用时间" :span="2">{{ detailData.callTime }}</NDescriptionsItem>
      </NDescriptions>

      <div>
        <div class="mb-8px font-medium">请求参数</div>
        <NCode :code="detailData.requestParams || '{}'" language="json" />
      </div>

      <div v-if="detailData.statusCode === 200">
        <div class="mb-8px font-medium">响应数据</div>
        <NCode :code="detailData.responseData || '[]'" language="json" />
      </div>

      <div v-if="detailData.errorMessage">
        <div class="mb-8px font-medium">错误信息</div>
        <NAlert type="error">{{ detailData.errorMessage }}</NAlert>
      </div>
    </div>
  </NModal>
</template>
